#pragma once

#include <string>
#include <vector>
#include <utility>

#include "../../precomp.h"
#include "../helper.hpp"

QFL_NAMESPACE_BEGIN
namespace text
{
	template < typename _CharT, typename _Traits >
	class ini_io
	{
    public:
        typedef _CharT char_type;
        typedef std::basic_string<_CharT,_Traits> string_type;
		typedef std::pair<int,int> index_pair;

	public:
		template<class _StringIt>
		ini_io(_StringIt first, _StringIt last)
		{
			boost::iterator_range<_StringIt> ls;
			while (first!=last)
			{
				ls = find_line_seperator(boost::make_iterator_range(first,last));
				lines_.push_back(string_type(first,ls.begin()));
				first = ls.end();
			}
		}

		void insert_line(int pos, const string_type& line)
		{
			if (pos>=(int)lines_.size())
			{
				lines_.push_back(line);
			}
			else
			{
				std::vector<string_type>::iterator it=lines_.begin();
				std::advance(it,pos);
				lines_.insert(it,line);
			}
		}

		size_t line_count() const { return lines_.size(); }

		string_type get_string(int n, const index_pair& ip) const
		{
			const string_type& line = lines_[n];
			return string_type(&line[ip.first],&line[ip.second]);
		}
		index_pair set_string(int n, const index_pair& ip, const string_type& str)
		{
			lines_[n].replace(ip.first,ip.second-ip.first,str);
			return make_pair(ip.first,ip.first+str.size());
		}

		index_pair get_section(int n) const
		{
			const string_type& line = lines_[n];
			typedef boost::iterator_range<const char_type*> it_range;
			it_range sr = ini_find_section(it_range(&line[0],&line[line.size()]));
			int i1 = sr.begin()-&line[0];
			int i2 = sr.end()-&line[0];
			return index_pair(i1,i2);
		}
		index_pair get_key(int n) const
		{
			const string_type& line = lines_[n];
			typedef boost::iterator_range<const char_type*> it_range;
			it_range sr = ini_find_key(it_range(&line[0],&line[line.size()]));
			int i1 = sr.begin()-&line[0];
			int i2 = sr.end()-&line[0];
			return index_pair(i1,i2);
		}
		index_pair get_value(int n) const
		{
			const string_type& line = lines_[n];
			typedef boost::iterator_range<const char_type*> it_range;
			it_range sr = ini_find_value(it_range(&line[0],&line[line.size()]));
			int i1 = sr.begin()-&line[0];
			int i2 = sr.end()-&line[0];
			return index_pair(i1,i2);
		}
	private:
		std::vector<string_type> lines_;
	};
}
QFL_NAMESPACE_END

